package com.cyzy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.mapper.AddressMapper;
import com.cyzy.pojo.Address;
import com.cyzy.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author LIGHT
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAddress(Address address) {
        prepareAddressFields(address);
        return this.save(address);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Address addAddressAndReturn(Address address) {
        prepareAddressFields(address);
        boolean saved = this.save(address);
        return saved ? address : null;
    }
    
    /**
     * 准备地址字段，设置状态并处理默认地址
     */
    private void prepareAddressFields(Address address) {
        // 确保状态字段为1（正常）
        if (address.getAddressStatus() == 0 || address.getAddressStatus() <= 0) {
            address.setAddressStatus(1L);
        }
        
        // 如果默认地址状态未设置，设为非默认(2)
        if (address.getAddressDefault() == 0) {
            address.setAddressDefault(2L);
        }
        
        // 如果设置为默认地址(1)，则需要先将该用户的所有地址设为非默认
        if (address.getAddressDefault() == 1L) {
            resetDefaultAddresses(address.getUserId());
        }
    }
    
    /**
     * 重置用户的所有默认地址
     */
    private void resetDefaultAddresses(Long userId) {
        this.update(
            new UpdateWrapper<Address>()
                .eq("user_id", userId)
                .eq("address_status", 1)
                .set("address_default", 2)
        );
    }

    @Override
    public boolean logicDeleteAddress(Long id) {
        Address address = this.getById(id);
        if (address == null) {
            return false;
        }
        address.setAddressStatus(0L);
        return this.updateById(address);
    }

    @Override
    public boolean updateAddress(Address address) {
        // 获取原地址信息
        Address originalAddress = this.getById(address.getAddressId());
        if (originalAddress == null) {
            return false;
        }
        
        // 保留原有状态
        address.setAddressStatus(originalAddress.getAddressStatus());
        
        // 如果未设置默认状态，保留原有默认状态
        if (address.getAddressDefault() == 0) {
            address.setAddressDefault(originalAddress.getAddressDefault());
        }
        
        // 如果设置为默认地址(1)，并且原来不是默认地址，则需要先将该用户的所有地址设为非默认
        if (address.getAddressDefault() == 1L && originalAddress.getAddressDefault() != 1L) {
            resetDefaultAddresses(address.getUserId());
        }
        
        return this.updateById(address);
    }

    @Override
    public boolean setDefaultAddress(Long userId, Long addressId) {
        // 获取地址信息并验证
        Address address = this.getById(addressId);
        if (address == null || !Objects.equals(address.getUserId(), userId)) {
            return false;
        }
        
        // 重置所有默认地址
        resetDefaultAddresses(userId);
        
        // 设置新的默认地址
        address.setAddressDefault(1L);
        return this.updateById(address);
    }

    @Override
    public List<Address> listValidAddressByUserId(Long userId) {
        return this.list(
            new QueryWrapper<Address>()
                .eq("user_id", userId)
                .eq("address_status", 1)
        );
    }
}
